package com.itic.mall.mobile.test;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.mall.system.store.storeInfo.persistence.model.StoreInfo;
import com.itic.mall.system.store.storeInfo.service.StoreInfoService;
import com.itic.mall.system.users.openstore.persistence.model.OpenStore;
import com.itic.mall.system.users.openstore.service.OpenStoreService;
import com.itic.mall.system.users.openstoreabnormal.persistence.model.OpenStoreAbnormal;
import com.itic.mall.system.users.openstoreabnormal.service.OpenStoreAbnormalService;
import com.itic.mall.system.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.users.usersmall.service.UsersMallService;

import net.sf.json.JSONArray;

@Controller
@RequestMapping(value = "/mobile/syncYuns")
public class SyncYiqiYuns {
	
	@Autowired
	private UsersMallService usersMallService;
	
	@Autowired
	private StoreInfoService storeInfoService;
	
	@Autowired
	private OpenStoreAbnormalService openStoreAbnormalService;
	
	@Autowired
	private OpenStoreService openStoreService;
	
	
	@RequestMapping(value = "/syncYiqiYuns")
	@ResponseBody
	public void syncYiqiYuns(String start,String length){
		String result =null;
		int successUserFlag = 0;
		int errorUserFlag = 0;
		
		int successStoreFlag = 0;
		int errorStoreFlag = 0;
		
		String url = "http://www.jhjvip.cn:8080/mall/mobile/test";
		String httpGet = HttpRequestUtils.httpGet(url+"/syncYuns"+"?start="+start+"&length="+length);
		
		//判断请求数据是否存在
		if(httpGet.contains("[")){
			JSONArray yuns = new net.sf.json.JSONArray();
			yuns = yuns.fromObject(httpGet);
			for( int k=0; k < yuns.size(); k++ ){
				net.sf.json.JSONObject jsonArrayYunsItem = yuns.getJSONObject(k);
				
				String id = jsonArrayYunsItem.getString("id");						//用户昵称	(店名称)
				String userNickName = jsonArrayYunsItem.getString("userNickName");	//用户昵称	(店名称)
				String createTime = jsonArrayYunsItem.getString("createTime");		//用户创建时间
				String unionId = jsonArrayYunsItem.getString("unionId");			//微信unionId
				String userPhone = jsonArrayYunsItem.getString("userPhone");		//用户手机号
				String userHeadImg = jsonArrayYunsItem.getString("userHeadImg");	//用户头像
				String invitingCode = jsonArrayYunsItem.getString("invitingCode");	//店主邀请码 唯一
				String money = jsonArrayYunsItem.getString("money");				//余额
				String preProfit = jsonArrayYunsItem.getString("preProfit");		//预计总收益
				String totalProfit = jsonArrayYunsItem.getString("totalProfit");	//累计总收益
				String openid = jsonArrayYunsItem.getString("openid");				//微信公众号OPENID
				String invitingId = jsonArrayYunsItem.getString("invitingId");		//邀请人ID
				String totalProduct = jsonArrayYunsItem.getString("totalProduct");	// 所有已成交的商品数量
				String successPeople = jsonArrayYunsItem.getString("successPeople");//成功获得一级的人数
				
				Double moneyDB = 0.00;
				Double preProfitDB = 0.00;
				Double totalProfitDB = 0.00;
				int successPeopleInt = 0;
				int totalProductInt = 0;
				
				if(!"".equals(money)){
					moneyDB=  Double.parseDouble(money);
				}
				if(!"".equals(preProfit)){
					preProfit = preProfit.replace(",",""); //去除逗号
					preProfitDB=  Double.parseDouble(preProfit);
				}
				if(!"".equals(totalProfit)){
					totalProfitDB=  Double.parseDouble(totalProfit);
				}
				if(!"".equals(successPeople)){
					successPeopleInt=  Integer.parseInt(successPeople);
				}
				if(!"".equals(totalProduct)){
					totalProductInt=  Integer.parseInt(totalProduct);
				}
				
				
				UsersMall usersMall = new UsersMall();
				//根据微信unionId 查询usermall （判断重复）
				UsersMall usersMallflag = usersMallService.getByUnionid(unionId);
				
				if(null == usersMallflag){
					//用户昵称（如果为空就是匿名用户）
					if("".equals(userNickName)){
						usersMall.setUserNickName("匿名用户");
					}else{
						String newUserNickName = removeFourChar(userNickName);//过滤昵称中的特殊字符
						usersMall.setUserNickName(newUserNickName); //用户昵称	(店名称)
					}
					usersMall.setId(id);
					usersMall.setCreateTime(DateHelper.parseDate(createTime));
					usersMall.setUnionid(unionId);					//微信unionId
					usersMall.setUserPhone(userPhone);				//用户手机号
					usersMall.setUserHeadImg(userHeadImg);			//用户头像
					usersMall.setInvitingCode(invitingCode);		//店主邀请码 唯一
					usersMall.setMoney(moneyDB);					//余额
					usersMall.setPreProfit(preProfitDB);			//预计总收益
					usersMall.setTotalProfit(totalProfitDB);		//累计总收益
					usersMall.setOpenid(openid);					//微信公众号OPENID
					usersMall.setParentId(invitingId);				//邀请人ID
					usersMall.setSuccessPeopleOne(successPeopleInt);//成功邀请到店主的人数(下级)
					usersMall.setType("002");						//是否为云店主（001为普通VIP用户，002为云店主）
					result = usersMallService.add(usersMall); 		//添加普通用户（方法）
					
					if("success".equals(result)){
						successUserFlag++; //成功同步user 个数
						syncTgw(id);//同步推广位
					}
					
					StoreInfo storeInfo = new StoreInfo();
					
					StoreInfo storeInfoFalg = storeInfoService.getByUserIdAndYunId(id);
					
					if(null == storeInfoFalg){
						String storeInfoId = IdGen.uuid();
						storeInfo.setId(storeInfoId);
						storeInfo.setCreateTime(DateHelper.parseDate(createTime));
						storeInfo.setUserId(id); //用户id
						storeInfo.setYunId(id);	 //云店主Id
						
						storeInfo.setPreProfit(preProfitDB);//预计总收益
						storeInfo.setTotalProfit(totalProfitDB);//累计总收益
						storeInfo.setOneLevelCount(successPeopleInt);//成功获得一级的人数
						
						if("".equals(userNickName)){
							usersMall.setUserNickName("匿名用户");//用户昵称
						}else{
							String newUserNickName = removeFourChar(userNickName);
							usersMall.setUserNickName(newUserNickName); //用户昵称	(店名称)
							storeInfo.setStoreName(newUserNickName); //店名称
							storeInfo.setNickName(newUserNickName);//开店人名称
						}
						storeInfo.setStoreImg(userHeadImg);//店铺头像
						storeInfo.setInviteCode(invitingCode); //店主邀请码 唯一
						storeInfo.setTotalProduct(totalProductInt);// 所有已成交的商品数量
						result = storeInfoService.add(storeInfo);
						
						if("success".equals(result)){
							successStoreFlag++; //成功添加云店主个数
						}
					}
					
				}else{
					
					if("001".equals(usersMallflag.getType())){
						
						UsersMall usersMalledit = new UsersMall();
											
						boolean result11 = usersMallService.updateUserMall(id,usersMallflag.getId(),userNickName,unionId,userPhone,userHeadImg,invitingCode,moneyDB,preProfitDB,totalProfitDB,openid,invitingId,successPeopleInt,"002"); //添加普通用户（方法）
						if(result11){
							errorUserFlag++; //失败修改个数
							syncTgw(id);//同步推广位
						}
						
					}else{
						boolean result11 = usersMallService.updateUserMall(id,usersMallflag.getId(),userNickName,unionId,userPhone,userHeadImg,invitingCode,moneyDB,preProfitDB,totalProfitDB,openid,invitingId,successPeopleInt,"002"); //添加普通用户（方法）
						
						if(result11){
							syncTgw(usersMallflag.getId());//同步推广位
						}
					}
					
					StoreInfo storeInfo = new StoreInfo();
					
					StoreInfo storeInfoFalg = storeInfoService.getByUserIdAndYunId(id);
					
					if(null == storeInfoFalg){
						String storeInfoId = IdGen.uuid();
						storeInfo.setId(storeInfoId);
						storeInfo.setCreateTime(DateHelper.parseDate(createTime));
						storeInfo.setUserId(id); //用户id
						storeInfo.setYunId(id);//云店主Id
						
						storeInfo.setPreProfit(preProfitDB);//预计总收益
						storeInfo.setTotalProfit(totalProfitDB);//累计总收益
						storeInfo.setOneLevelCount(successPeopleInt);//成功获得一级的人数
						
						if("".equals(userNickName)){
							usersMall.setUserNickName("匿名用户");//用户昵称
						}else{
							String newUserNickName = removeFourChar(userNickName);
							usersMall.setUserNickName(newUserNickName); //用户昵称	(店名称)
							
							storeInfo.setStoreName(newUserNickName); //店名称
							storeInfo.setNickName(newUserNickName);//开店人名称
						}
						
						storeInfo.setStoreImg(userHeadImg);//店铺头像
						storeInfo.setInviteCode(invitingCode); //店主邀请码 唯一
						storeInfo.setTotalProduct(totalProductInt);// 所有已成交的商品数量
						
						result =  storeInfoService.add(storeInfo);
						
						if("success".equals(result)){
							errorStoreFlag++; //成功添加云店主个数
						}
					}
					System.out.println("已存在——-------------"+unionId);
				}
				System.out.println(jsonArrayYunsItem);
			}
		}
		
		
		System.out.println("成功添加用户" + successUserFlag);
		System.out.println("修改用户" + errorUserFlag);
		System.out.println("成功添加云店" + successStoreFlag);
		System.out.println("修改云店" + errorStoreFlag);
	}
	
	/**
	  * 同步一期
	  * @author 王文鑫
	  * @date 2018年1月25日 下午4:39:00
	  * @param userId
	  * @return
	  */
	 public void syncTgw(String userId){
		String url = "http://www.jhjvip.cn:8080/mall/mobile/test";
		String httpGet = HttpRequestUtils.httpGet(url+"/syncTgw"+"?userId="+userId);
		JSONArray tgws = new net.sf.json.JSONArray();
		//判断返回数据是否存在
		if(httpGet.contains("[")){
			tgws = tgws.fromObject(httpGet);
			for( int k=0; k < tgws.size(); k++ ){
				net.sf.json.JSONObject jsonArrayTgwsItem = tgws.getJSONObject(k);
				
				String id = jsonArrayTgwsItem.getString("id");  					//主键
				String tgwId = jsonArrayTgwsItem.getString("tgwId");				//推广位ID
				String tgwName = jsonArrayTgwsItem.getString("tgwName");			//推广位名称
				String tgwPid = jsonArrayTgwsItem.getString("tgwPid");  			//推广位PID
				String regTime = jsonArrayTgwsItem.getString("regTime");			//创建时间
				String unionid = jsonArrayTgwsItem.getString("unionid");			//微信ID
				String phone = jsonArrayTgwsItem.getString("phone");				//电话
				String userId_new = jsonArrayTgwsItem.getString("userId");			//店主ID
				String userNickName = jsonArrayTgwsItem.getString("userNickName");	//店主昵称
				
				//如果含有逗号 是异常数据
				if(tgwName.contains(",")){
					OpenStoreAbnormal openStoreAbnormal = new OpenStoreAbnormal();
					OpenStoreAbnormal openStoreAbnormalFlag =  openStoreAbnormalService.getById(id);
					//判断是否重复
					if(null == openStoreAbnormalFlag){
						openStoreAbnormal.setId(id);
						openStoreAbnormal.setTgwId(tgwId);
						openStoreAbnormal.setTgwPid(tgwPid);
						Date reTimeD = new Date();
						if("".equals(regTime)){
							 reTimeD = DateHelper.parseDate(regTime);
						}
						openStoreAbnormal.setRegTime(reTimeD);
						openStoreAbnormal.setPhone(phone);
						openStoreAbnormal.setUserId(userId_new);
						openStoreAbnormal.setUserNickName(userNickName);
						openStoreAbnormal.setTgwName(tgwName);
						openStoreAbnormalService.add(openStoreAbnormal);
					}
				}else{
					OpenStore openStore = new OpenStore();
					
					OpenStore openStoreflag =  openStoreService.getById(id);
					
					//判断是否重复
					if(null == openStoreflag){
						openStore.setId(id);
						openStore.setTgwId(tgwId);
						openStore.setTgwPid(tgwPid);
						
						Date reTimeD = new Date();
						if("".equals(regTime)){
							 reTimeD = DateHelper.parseDate(regTime);
						}
						openStore.setRegTime(reTimeD);
						openStore.setPhone(phone);
						openStore.setUserId(userId_new);
						openStore.setUserNickName(userNickName);
						openStore.setTgwName(tgwName);
						openStore.setStatus("1"); 		//状态（0审核中，1开店成功，2开店失败） 
						openStore.setType("jd");
						openStoreService.add(openStore);
					}
				}
			}
		}
		
	 }
	
	/**
	 * 过滤微信昵称特殊字符
	 * @author 王文鑫
	 * @date 2018年1月22日 下午5:14:44
	 * @param content
	 * @return
	 */
	 public String removeFourChar(String content) {
        byte[] conbyte = content.getBytes();
        for (int i = 0; i < conbyte.length; i++) {
            if ((conbyte[i] & 0xF8) == 0xF0) {
                for (int j = 0; j < 4; j++) {                          
                    conbyte[i+j]=0x30;                     
                }  
                i += 3;
            }
        }
        content = new String(conbyte);
        return content.replaceAll("0000", "");
    }
	
}
